<!--
 * @Author: Rain
 * @Date: 2023/09/26 16:43:34
 * @LastEditTime: 2023/11/04 19:00:50
 * @Description: Do Something
-->
<template>
  <div class="flex w-full grid-cols-6 grid gap-10">
    <div
      v-for="(item, index) in fileList"
      :key="index"
      class="relative border border-solid border-gray-300 w-88 h-88"
    >
      <video class="avatar" :src="item.filePath" />
      <i
        class="el-icon-circle-close cursor-pointer absolute top-0 right-0"
        @click="deleteFile(index)"
      />
    </div>
    <el-upload
      ref="uploadFile"
      class="avatar-uploader"
      :auto-upload="false"
      action=""
      multiple
      :file-list="fileList"
      :show-file-list="false"
      :http-request="handleUpload"
      :on-change="beforeAvatarUpload"
      accept="video/*"
    >
      <i class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
import { upload } from '@/utils/upload'
import { mapGetters } from 'vuex'
export default {
  props: {
    files: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      file: null,
      fileType: '',
      fileList: []
    }
  },
  computed: {
    ...mapGetters(['fileUploadApi'])
  },
  watch: {
    files: {
      handler(val) {
        this.fileList = val
      }
    }
  },
  methods: {
    beforeAvatarUpload(file, fileList) {
      const flag = fileList.some((item) => item.size / 1024 / 1024 > 100)
      if (flag) {
        this.$message.error('上传附件大小不能超过100MB!')
        return
      }
      this.fileList = fileList.map((item) => {
        item.filePath = URL.createObjectURL(item.raw)
        return item
      })
      this.$emit('upload', this.fileList)
    },
    deleteFile(index) {
      this.fileList.splice(index, 1)
    },
    handleUpload(callback) {
      return Promise.all(
        this.fileList.map((item) => {
          return new Promise((resolve, reject) => {
            if (!item.raw) {
              resolve(item.filePath)
              return
            }
            upload(this.fileUploadApi, item.raw, { name: item.name }).then((res) => {
              const { data: { path }} = res
              resolve(path)
            })
          })
        })
      )
        .then((res) => {
          return res
        })
        .catch((err) => {
          console.log(err)
        })
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 88px;
  height: 88px;
  line-height: 88px;
  text-align: center;
}
.avatar {
  width: 88px;
  height: 88px;
  display: block;
}
.el-upload__tip {
  font-size: 12px;
  color: #409eff;
}
video {
  object-fit: cover;
  width: 100%;
  height: 100%;
  outline: none;
}
</style>
